<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>响应式计算器</title>
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- 配置Tailwind自定义颜色 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#333333',
                        accent: '#4A90E2',
                        light: '#F5F5F5',
                        'light-gray': '#E0E0E0'
                    }
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .calc-btn {
                @apply rounded-md transition-all duration-150 flex items-center justify-center;
            }
            .calc-btn:active {
                @apply scale-95;
            }
            .calc-btn:hover {
                @apply brightness-95;
            }
            .display-area {
                @apply overflow-x-auto whitespace-nowrap;
            }
        }
    </style>
</head>

<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <!-- 计算器容器 - 响应式设计核心 -->
    <div class="bg-white shadow-lg rounded-lg overflow-hidden w-full max-w-md mx-auto">
        <!-- 单行显示屏区域 - 响应式字体大小 -->
        <div class="bg-primary text-white p-4 sm:p-6">
            <div id="display"
                class="text-right font-medium min-h-[40px] sm:min-h-[50px] display-area text-3xl sm:text-4xl"></div>
        </div>

        <!-- 按钮区域 - 响应式网格和间距 -->
        <div class="p-1 sm:p-2 grid grid-cols-4 gap-1 sm:gap-2">
            <!-- 第一行 -->
            <button class="calc-btn bg-light-gray text-primary py-2 sm:py-3 text-lg sm:text-xl"
                data-action="clear">C</button>
            <button class="calc-btn bg-light-gray text-primary py-2 sm:py-3 text-lg sm:text-xl"
                data-action="delete">⌫</button>
            <button class="calc-btn bg-light-gray text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="operator"
                data-value="%">%</button>
            <button class="calc-btn bg-accent text-white py-2 sm:py-3 text-lg sm:text-xl" data-action="operator"
                data-value="/">÷</button>

            <!-- 第二行 -->
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="7">7</button>
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="8">8</button>
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="9">9</button>
            <button class="calc-btn bg-accent text-white py-2 sm:py-3 text-lg sm:text-xl" data-action="operator"
                data-value="*">×</button>

            <!-- 第三行 -->
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="4">4</button>
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="5">5</button>
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="6">6</button>
            <button class="calc-btn bg-accent text-white py-2 sm:py-3 text-lg sm:text-xl" data-action="operator"
                data-value="-">-</button>

            <!-- 第四行 -->
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="1">1</button>
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="2">2</button>
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value="3">3</button>
            <button class="calc-btn bg-accent text-white py-2 sm:py-3 text-lg sm:text-xl" data-action="operator"
                data-value="+">+</button>

            <!-- 第五行 -->
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl col-span-2"
                data-action="number" data-value="0">0</button>
            <button class="calc-btn bg-light text-primary py-2 sm:py-3 text-lg sm:text-xl" data-action="number"
                data-value=".">.</button>
            <button class="calc-btn bg-accent text-white py-2 sm:py-3 text-lg sm:text-xl"
                data-action="equals">=</button>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            class Calculator {
                constructor(displayId) {
                    this.display = document.getElementById(displayId);
                    this.currentValue = '0';      // 当前输入的数字
                    this.expression = '';         // 已输入的表达式部分
                    this.lastInputType = null;    // 'number', 'operator', 'equals'
                    this.calculated = false;      // 是否刚计算完结果
                    this.awaitingNumber = false;  // 是否正在等待输入新数字
                    this.initEventListeners();
                    this.updateDisplay();
                }

                // 更新显示屏
                updateDisplay() {
                    let displayText;

                    // 显示逻辑
                    if (this.calculated) {
                        displayText = this.currentValue;
                    } else if (this.expression && this.awaitingNumber) {
                        displayText = this.expression;  // 只显示表达式
                    } else if (this.expression) {
                        displayText = `${this.expression} ${this.currentValue}`;
                    } else {
                        displayText = this.currentValue;
                    }

                    // 根据屏幕尺寸动态调整超长数字显示
                    const screenWidth = window.innerWidth;
                    const maxLength = screenWidth < 360 ? 8 : screenWidth < 640 ? 10 : 14;

                    if (displayText.length > maxLength && !isNaN(parseFloat(displayText))) {
                        displayText = parseFloat(displayText).toExponential(6);
                    }

                    this.display.textContent = displayText;
                }

                // 处理数字输入
                handleNumber(number) {
                    // 处理错误状态或计算后状态
                    if (this.currentValue === "错误" || this.calculated) {
                        this.currentValue = '0';
                        this.expression = '';
                        this.calculated = false;
                    }

                    // 如果正在等待输入新数字，重置当前值
                    if (this.awaitingNumber) {
                        this.currentValue = '0';
                        this.awaitingNumber = false;
                    }

                    // 处理小数点
                    if (number === '.' && this.currentValue.includes('.')) return;

                    // 处理数字输入
                    this.currentValue = this.currentValue === '0' && number !== '.'
                        ? number
                        : this.currentValue + number;

                    this.lastInputType = 'number';
                    this.updateDisplay();
                }

                // 处理运算符
                handleOperator(ops) {
                    // 处理错误状态
                    if (this.currentValue === "错误") {
                        this.clearAll();
                        return;
                    }

                    // 计算后输入运算符：用结果作为新表达式的开始
                    if (this.calculated) {
                        this.expression = this.currentValue + ' ' + ops;
                        this.calculated = false;
                        this.awaitingNumber = true;
                        this.lastInputType = 'operator';
                        this.updateDisplay();
                        return;
                    }

                    // 首次输入运算符：将当前值和运算符加入表达式
                    if (!this.expression && this.lastInputType === 'number') {
                        this.expression = this.currentValue + ' ' + ops;
                        this.awaitingNumber = true;
                        this.lastInputType = 'operator';
                        this.updateDisplay();
                    }
                    // 连续输入运算符：替换最后一个运算符
                    else if (this.expression && this.lastInputType === 'operator') {
                        this.expression = this.expression.trim().slice(0, -1) + ops;
                        this.updateDisplay();
                    }
                    // 已有表达式且输入了数字后再输入运算符
                    else if (this.expression && this.lastInputType === 'number') {
                        this.expression += ' ' + this.currentValue + ' ' + ops;
                        this.awaitingNumber = true;
                        this.lastInputType = 'operator';
                        this.updateDisplay();
                    }
                }

                // 计算结果
                calculate() {
                    // 防止在没有数字输入时计算
                    if (this.lastInputType !== 'number') return;

                    try {
                        let result;

                        // 有表达式时进行计算
                        if (this.expression) {
                            // 构建完整表达式
                            const fullExpr = this.expression + ' ' + this.currentValue;

                            // 转换为JavaScript可识别的运算符
                            const jsExpr = fullExpr
                                .replace(/×/g, '*')
                                .replace(/÷/g, '/')
                                .replace(/%/g, '%');

                            // 计算结果
                            result = eval(jsExpr);
                        } else {
                            // 没有表达式时，结果就是当前值
                            result = parseFloat(this.currentValue);
                        }

                        // 处理结果格式
                        if (Number.isInteger(result)) {
                            this.currentValue = result.toString();
                        } else {
                            // 保留最多6位小数，并去除末尾多余的0
                            this.currentValue = result.toFixed(6).replace(/\.?0+$/, "");
                        }

                        this.expression = '';
                        this.awaitingNumber = false;
                        this.lastInputType = 'equals';
                        this.calculated = true;
                    } catch (error) {
                        this.currentValue = "错误";
                        this.expression = '';
                        this.awaitingNumber = false;
                    }

                    this.updateDisplay();
                }

                // 清除所有
                clearAll() {
                    this.currentValue = '0';
                    this.expression = '';
                    this.lastInputType = null;
                    this.calculated = false;
                    this.awaitingNumber = false;
                    this.updateDisplay();
                }

                // 删除最后一个字符
                deleteLast() {
                    // 处理错误状态或计算后状态
                    if (this.currentValue === "错误" || this.calculated) {
                        this.clearAll();
                        return;
                    }

                    // 如果正在等待输入新数字，删除最后一个运算符
                    if (this.awaitingNumber && this.expression) {
                        const parts = this.expression.trim().split(' ');
                        if (parts.length > 0) {
                            parts.pop(); // 移除运算符
                            this.expression = parts.join(' ') + (parts.length > 0 ? ' ' : '');
                        } else {
                            this.expression = '';
                        }
                        this.awaitingNumber = false;
                        this.lastInputType = 'number';
                    }
                    // 否则删除当前值的最后一个字符
                    else if (this.currentValue.length > 1) {
                        this.currentValue = this.currentValue.slice(0, -1);
                    } else {
                        this.currentValue = '0';
                    }

                    this.updateDisplay();
                }

                // 初始化事件监听
                initEventListeners() {
                    // 按钮点击事件
                    document.querySelectorAll('button').forEach(button => {
                        button.addEventListener('click', () => {
                            const action = button.dataset.action;
                            const value = button.dataset.value;

                            switch (action) {
                                case 'number': this.handleNumber(value); break;
                                case 'operator': this.handleOperator(value); break;
                                case 'equals': this.calculate(); break;
                                case 'clear': this.clearAll(); break;
                                case 'delete': this.deleteLast(); break;
                            }
                        });
                    });

                    // 键盘支持
                    document.addEventListener('keydown', (e) => {
                        if (['+', '-', '*', '/', '%', '=', '.', 'Enter', 'Escape', 'Backspace'].includes(e.key)) {
                            e.preventDefault();
                        }

                        if (/[0-9]/.test(e.key)) this.handleNumber(key);
                        else if (e.key === '.') this.handleNumber('.');
                        else if (['+', '-', '*', '/', '%'].includes(e.key)) {
                            const displayOp = e.key === '*' ? '×' : e.key === '/' ? '÷' : e.key;
                            this.handleOperator(displayOp);
                        }
                        else if (e.key === '=' || e.key === 'Enter') this.calculate();
                        else if (e.key === 'Backspace') this.deleteLast();
                        else if (e.key === 'Escape') this.clearAll();
                    });

                    // 屏幕尺寸变化时更新显示
                    window.addEventListener('resize', () => this.updateDisplay());
                }
            }

            // 初始化计算器实例
            new Calculator('display');
        });
    </script>
</body>

</html>